// import fetch from 'dva/fetch';
import React, { Component } from 'react';
import { Layout, Tabs, Form, Modal, Spin } from 'antd';
import styles from '../../../index.less';
import Toolbar from '../../Common/ToolBar/ToolBar';
import TabFinancePeriod from './TabFinancePeriod';
import TabsSalesBuyer from './TabSalesBuyer';
import TabFinanceOffer from './TabFinanceOffer';
import TabReceiptsNum from './TabReceiptsNum';
import TabSysParam from './TabSysParam';
import * as config from '../../../utils/config';
import * as commonFunc from '../../Common/commonFunc';
import baseHigher from '../../Common/baseHigher';
import PpopupPan from '../../../routes/ppopupPan/ppopupPan';

const { confirm } = Modal;
const { Header, Content } = Layout;
const { TabPane } = Tabs;

class SystemSetting extends Component {
  constructor(props) {
    super(props);
    this.state = {
      btnData: config.btnSysData, /* 工具栏按钮 */
      masterConfig: { sId: '' }, // 主表 + 从表 配置
      sId: '', /* 业务数据ID */
      sActiveId: '', /* 窗体Id */
      loading: false,
      modalVisible: false, /* 弹窗显示状态 */
      modalPanel: {}, /* 弹窗面板属性 */
      tabFinancePeriod: '', /* 会计期间 */
      tabReceiptsNum: '', /* 单据编号设置 */
      tabSalesBuyer: '', /* 销售采购生产参数 */
      tabFinanceOffer: '', /* 财务仓库报价参数 */
      tabSysParam: '', /* 系统参数 */
      accountData: [],
      billnoData: [],
      systemData: [],
      oldBillNoData: [],
      listRecordKey: { accountDataKey: '', billnoDataKey: '' }, /* 列表弹窗当前操作行,内部属性根据模块不同自定义 */
      iYear: new Date().getFullYear(), /* 年份 */
    };
  }

  componentWillReceiveProps(nextProps) {
    const { dataList } = nextProps.content;
    /* const { gdsformconst, report } = nextProps;
    if (this.state.gdsformconst.length === 0) {
      this.setState({
        gdsformconst,
      });
    }
    if (this.state.report.length === 0) {
      const btnDataChild = [];
      report.forEach((child, i) => {
        btnDataChild.push({
          sName: `BtnPrint.${i}`,
          showName: child.sReportName,
          bVisible: true,
          sActiveId: '',
          sId: child.sId,
        });
      });
      this.setState({ btnDataChild, report });
    } */
    /* 配置 */
    const {
      sDataListTabId, urlData, formRoute, loading, paneType, checkedId, sParentId, sFilterOrderBy, bFilter, pageSize, pages, sListFormmasterId, currentData, newkey,
    } = dataList;
    if (urlData !== undefined && Object.keys(urlData).length > 0 && paneType !== undefined && paneType !== '' && nextProps.sTabId === sParentId) {
      const paneKey = new Date().getTime().toString();
      const pane = {
        copyToData: dataList.copyToData, /* 复制到数据 */
        title: urlData.sMenuName,
        route: urlData.sName,
        formId: urlData.sId,
        checkedId,
        key: paneKey,
        sFilterOrderBy,
        bFilter,
        pageSize,
        pages,
        sListFormmasterId,
        currentData,
        newkey,
      };
      this.props.onAddPane(pane);
      return;
    }
    /* 数据Id */
    const { formId } = nextProps;
    /* 窗体全部配置 */
    const masterConfig = commonFunc.getWindowConfig('syssystemsettings', nextProps.formData);
    /* 弹出窗数据返回,渲染数据并关闭弹出框 */
    if ((nextProps.app.ppopupPane !== undefined &&
      nextProps.app.ppopupPane.mainConfig !== undefined) ? (nextProps.sTabId === nextProps.app.ppopupPane.mainConfig.key
      && nextProps.formRoute === nextProps.app.ppopupPane.mainConfig.route) : false) {
      const { resultValue } = nextProps.app.ppopupPane;
      const { modalType } = nextProps.app.ppopupPane;
      /* 通用弹窗数据返值处理 */
      if ((resultValue !== undefined) && modalType === 'ppopup') {
        /* 数据集名 */
        const { dataName } = nextProps.app.ppopupPane;
        /* 数据集类型，对象型为Map 数组型为List */
        const { dataType } = nextProps.app.ppopupPane;
        const data = this.state[`${dataName}`];
        if (dataType === 'Map') {
          for (const key of Object.keys(resultValue)) {
            const index = data.findIndex(item => (item.sName === key));
            data[index].sValue = resultValue[key];
          }
          this.setState({ [`${dataName}`]: data, modalVisible: false });
        } else if (dataType === 'List') {
          data.map((item) => {
            if ((item.sId === undefined ? item.key : item.sId) === this.state.listRecordKey[`${dataName}Key`]) {
              for (const key of Object.keys(resultValue)) {
                item[`${key}`] = resultValue[`${key}`];
              }
            }
            return item;
          });
          /* 弹窗数据回填后，清空listRecordKey 避免数据污染 */
          this.setState({
            [`${dataName}`]: data,
            modalVisible: false,
            listRecordKey: { accountDataKey: '', billnoDataKey: '' },
          });
        }
        /* 弹出框关闭 */
        this.props.onRemoveModalPane({});
        return;
      }
    }
    if (nextProps.sTabId === sDataListTabId && nextProps.formRoute === formRoute && nextProps.formData.length > 0) {
      if (loading) return;
      if (dataList.returnType !== undefined && dataList.returnType === 'CUD') {
        this.handleRefresh();
        return;
      }
      /* 窗体显示配置 */
      const masterShowConfig = commonFunc.getSysConfigCondition(masterConfig.gdsconfigformslave, 'bVisible');
      if (this.state.sActiveId === '') {
        const materielPan = nextProps.app.currentPane;
        /* 获取工具栏, 主表，页签标题 */
        this.setState({ toolProps: nextProps });
        const { formData } = urlData;
        /* 窗体配置 */
        const mainTable = formData.filter(item => (item.sTbName.toLowerCase() === 'syssystemsettings'))[0];
        /* 匹配主表 */
        const mainConfig = mainTable.gdsconfigformslave;
        const tabFinancePeriod = mainConfig.filter(item => (item.sControlName.toLowerCase() === 'tabfinanceperiod'))[0];
        const tabReceiptsNum = mainConfig.filter(item => (item.sControlName.toLowerCase() === 'tabreceiptsnum'))[0];
        const tabSalesBuyer = mainConfig.filter(item => (item.sControlName.toLowerCase() === 'tabsalesbuyer'))[0];
        const tabFinanceOffer = mainConfig.filter(item => (item.sControlName.toLowerCase() === 'tabfinanceoffer'))[0];
        const tabSysParam = mainConfig.filter(item => (item.sControlName.toLowerCase() === 'tabsysparam'))[0];
        /* 从表配置 */
        this.setState({
          formData,
          mainTable,
          sId: materielPan.checkedId !== undefined ? materielPan.checkedId : '',
          sActiveId: formId,
          mainConfig,
          tabFinancePeriod: tabFinancePeriod !== undefined ? tabFinancePeriod : {
            showName: '会计期间',
            sId: new Date().getTime() + 1,
          }, /* 页签名 */
          tabSalesBuyer: tabSalesBuyer !== undefined ? tabSalesBuyer : {
            showName: '销售采购生产参数',
            sId: new Date().getTime() + 2,
          },
          tabFinanceOffer: tabFinanceOffer !== undefined ? tabFinanceOffer : {
            showName: '财务仓库报价参数',
            sId: new Date().getTime() + 3,
          },
          tabReceiptsNum: tabReceiptsNum !== undefined ? tabReceiptsNum : {
            showName: '单据编号设置',
            sId: new Date().getTime() + 4,
          },
          tabSysParam: tabSysParam !== undefined ? tabSysParam : { showName: '系统参数', sId: new Date().getTime() + 5 },
        });
        this.setState({ masterConfig, masterShowConfig });
      } else if (dataList.returnType !== undefined && dataList.returnType === 'data'
        && dataList.componentName.indexOf('sysaccountperiod') <= 0
        && dataList.componentName.indexOf('sysbillnosettings') <= 0) {
        const systemData = [];
        const sysData = Object.keys(urlData).length > 0
          ? urlData : [];
        for (const key of Object.keys(masterShowConfig)) {
          const { sControlName } = masterShowConfig[key];
          const data = sysData.filter(item => item.sName === sControlName.substring(1));
          if (data.length > 0) {
            data[0].sName = masterShowConfig[key].sControlName;
            systemData.push(data[0]);
          }
        }
        this.setState({ systemData, loading: false });
      }
    }
    if (dataList.returnType !== undefined
      && dataList.returnType === 'data'
      && dataList.componentName === 'sysaccountperiod') {
      const accountData = Object.keys(urlData).length > 0
        ? urlData : [];
      this.setState({ accountData, loading: false });
    }
    if (dataList.returnType !== undefined
      && dataList.returnType === 'data'
      && dataList.componentName === 'sysbillnosettings') {
      const billnoData = Object.keys(urlData).length > 0
        ? urlData : [];
      const oldBillNoData = this.state.oldBillNoData.length > 0 ? this.state.oldBillNoData : [...billnoData];
      this.setState({ billnoData, oldBillNoData, loading: false });
    }
  }
  shouldComponentUpdate(nextProps) {
    let flag = true;
    /* 追加弹出框数值回填放行判断ppopupPane */
    if (nextProps.sTabId === nextProps.app.currentPane.key || ((nextProps.app.ppopupPane !== undefined
      && nextProps.app.ppopupPane.mainConfig !== undefined)
      ? nextProps.sTabId === nextProps.app.ppopupPane.mainConfig.key : false)) {
      flag = true;
    } else {
      flag = false;
    }
    return flag;
  }

  /* 刷新 */
  handleRefresh = () => {
    const { dispatch } = this.props;
    const {
      masterConfig, sId, sActiveId, formData,
    } = this.state;
    /* 表Id */
    const mainId = masterConfig.sId;
    /* 业务数据Id */
    const value = { sId };
    const sTabId = this.props.app.currentPane.key;
    /* 从表value */
    const slaveValue = {
      sSqlCondition: {
        sParentId: sId,
      },
    };
    const perValue = {
      sSqlCondition: {
        sParentId: sId,
      },
      bFilter: [{
        bFilterName: 'sPeriodId',
        bFilterValue: this.state.iYear,
        bFilterCondition: 'like',
      }],
    };
    const accountConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'sysaccountperiod'))[0];
    const billnoConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'sysbillnosettings'))[0];
    const accountsId = accountConfig.sId;
    const billnosId = billnoConfig.sId;
    const mainDataUrl =
      `${config.server_host}syssystem/getSyssystemDataByFormcustomId/${mainId}?sModelsId=${sActiveId}`;
    dispatch({
      type: 'content/getUrlPostData',
      payload: {
        url: mainDataUrl,
        sTabId,
        componentName: 'syssystemsettings',
        value,
        formRoute: '/syssystemsettings',
        returnType: 'data',
      },
    });
    const accountDataUrl =
      `${config.server_host}business/getBusinessDataByFormcustomId/${accountsId}?sModelsId=${sActiveId}`;
    dispatch({
      type: 'content/getUrlPostData',
      payload: {
        url: accountDataUrl,
        sTabId,
        componentName: 'sysaccountperiod',
        value: perValue,
        formRoute: '/sysaccountperiod',
        returnType: 'data',
      },
    });
    const billnoDataUrl =
      `${config.server_host}business/getBusinessDataByFormcustomId/${billnosId}?sModelsId=${sActiveId}`;
    dispatch({
      type: 'content/getUrlPostData',
      payload: {
        url: billnoDataUrl,
        sTabId,
        componentName: 'sysbillnosettings',
        value: slaveValue,
        formRoute: '/sysbillnosettings',
        returnType: 'data',
      },
    });
  };

  /* 取消 */
  handleCancel =(type) => {
    const onhandleOk = this.handleOk;
    confirm({
      title: '确定要取消?',
      onOk() {
        onhandleOk(type);
      },
      onCancel() {},
    });
  };
  /* 数据自动变更 */
  handleFormChange = (value) => {
    const keys = Object.keys(value)[0];
    const { systemData, masterShowConfig } = this.state;
    const showConfig = masterShowConfig.filter(item => (item.sName === keys))[0];
    if (showConfig !== undefined && showConfig.sDropDownType === 'sql') return;
    /* 数据处理,手动清空数据时数据会为undefined，不符合数据赋值要求 */
    const changeValue = commonFunc.changeSystemValue(value);
    for (const key of Object.keys(changeValue)) {
      const index = systemData.findIndex(item => item.sName === key);
      systemData[index].sValue = changeValue[key];
    }
    this.setState({
      systemData,
    });
  };
  /* 确认取消 */
  handleOk = () => {
    let lastIndex = -1;
    this.props.app.panes.forEach((pane, i) => {
      if (pane.key === this.props.app.currentPane.key) {
        lastIndex = i - 1;
      }
    });

    const panes = this.props.app.panes.filter(pane => pane.key !== this.props.app.currentPane.key);
    let currentPane;
    if (lastIndex >= 0) {
      currentPane = panes[lastIndex];
    } else if (lastIndex === -1 && panes.length > 0) {
      currentPane = panes[lastIndex + 1];
    } else {
      currentPane = { title: '', route: '', key: '0' };
    }
    this.props.onRemovePane(panes, currentPane);
  };
  /* 保存 */
  handleSubmit() {
    const { dispatch } = this.props;
    /* 业务数据Id */
    const sTabId = this.props.app.currentPane.key;
    this.form.validateFieldsAndScroll((err, formValue) => {
      const inputValue = [];
      const { systemData } = this.state;
      for (const key of Object.keys(formValue)) {
        const newData = {};
        const sName = key.substring(1);
        newData.sValue = formValue[key];
        newData.sName = sName;
        newData.handleType = 'update';
        const showConfig = systemData.filter(item => (item.sName === key))[0];
        newData.sId = showConfig.sId;
        inputValue.push(newData);
      }
      if (!err) {
        const { sActiveId } = this.state;
        const dataUrl = `${config.server_host}business/addUpdateDelBusinessData?sModelsId=${sActiveId}`;
        const value = {
          data: [{
            sTable: 'syssystemsettings',
            column: inputValue,
          }, {
            sTable: 'sysaccountperiod',
            column: this.state.accountData,
          }, {
            sTable: 'sysbillnosettings',
            column: this.state.billnoData,
          }],
          sClientType: '1',
        };
        dispatch({
          type: 'content/getUrlPostDataSys',
          payload: {
            url: dataUrl,
            sTabId,
            value,
            componentName: 'syssystemsettings',
            formRoute: '/syssystemsettings',
            returnType: 'CUD',
          },
        });
      }
    });
  }
  /* 会计期间表单自动变更 */
  handleAccountData = (value) => {
    this.setState({
      accountData: value,
    });
  };
  /* 单据编号表单自动变更 */
  handleBillNoData = (value) => {
    const billnoDataState = [...this.state.billnoData];
    const { oldBillNoData } = this.state;
    const billnoDataDel = billnoDataState.filter(item => (item.handleType === 'del'));
    const billnoDataSeaDel = value.filter(item => (item.handleType === 'del'));
    const billnoDataUnp = value.filter(item => (item.handleType === 'update'));
    if (billnoDataUnp.length > 0) {
      const index = oldBillNoData.findIndex(item => (item.key === billnoDataUnp[0].key));
      [oldBillNoData[index]] = billnoDataUnp;
    }
    if (billnoDataSeaDel.length > 0) {
      const indexDel = oldBillNoData.findIndex(item => (item.key === billnoDataSeaDel[0].key));
      oldBillNoData.splice(indexDel, 1);
    }
    const billnoData = [...billnoDataDel, ...value];
    this.setState({
      billnoData,
      oldBillNoData,
    });
  }

  handleForm = (form) => {
    this.form = form;
  }

  /* 弹窗关闭 */
  handlePpopUpPaneCancel = () => {
    /* 弹窗类型，下拉/弹窗 */
    const { modalType } = this.props.app.ppopupPane;
    /* 数据集名 */
    const { dataName } = this.props.app.ppopupPane;
    const data = this.state[`${dataName}`];
    /* 如果为下拉新增则下拉值重置为空 */
    if (modalType === 'select') {
      /* 数据集类型，对象型为Map 数组型为List */
      const { dataType } = this.props.app.ppopupPane;
      const { mainKey } = this.props.app.ppopupPane;
      /* 窗体关闭时下拉重置为空,避免下拉项停留在NEW选项 */
      if (dataType === 'Map' && data[`${mainKey}`] === '000') {
        data[`${mainKey}`] = ' ';
      } else if (dataType === 'List') {
        data.map((item) => {
          if (item.key === this.state.listRecordKey[`${dataName}Key`] && item[`${mainKey}`] === '000') {
            item[`${mainKey}`] = ' ';
          }
          return item;
        });
      }
    }
    /* 置空models中弹窗面板 */
    this.props.onRemoveModalPane({});
    /* 隐藏弹窗面板 */
    this.setState({
      modalVisible: false,
      [`${dataName}`]: data,
      listRecordKey: { accountDataKey: '', billnoDataKey: '' },
    });
  };

  /* 弹窗面板状态更改 */
  handleModalPane = (value) => {
    this.setState({ modalVisible: value.modalVisible });
  };

  /* 用于返回列表编辑框弹窗所属行主键 */
  handleRecordKey = (value) => {
    const { listRecordKey } = this.state;
    this.setState({ listRecordKey: { ...listRecordKey, ...value } });
  };

  /* 非列表联动下拉 */
  handleSelectChange = (value, dataType, dataName) => {
    /* 数据集类型，对象型为Map 数组型为List */
    const data = this.state[`${dataName}`];
    if (dataType === 'Map') {
      /* 系统参数此处和其余非列表联动下拉不一样所以处理方式有区别 */
      for (const item of value) {
        const changeData = data.filter(child => (child.sName === `${item.key}`));
        changeData.value = item.value;
      }
      this.setState({ [`${dataName}`]: data });
    }
  };

  handleiYear = (iYear) => {
    this.setState({
      iYear,
    });
  };

  render() {
    const { pageLoading } = this.props;
    const { props, state } = this;
    const { loading } = this.state;
    return (
      <div>
        <Spin spinning={loading}>
          {pageLoading ? '' :
          <div>
            <SystemSettingComponent
              {...props}
              {...state}
              handleSubmit={this.handleSubmit.bind(this)}
              handleOk={this.handleOk.bind(this)}
              handleCancel={this.handleCancel.bind(this)}
              onChange={this.handleFormChange.bind(this)}
              handleForm={this.handleForm.bind(this)}
              handleAccountData={this.handleAccountData.bind(this)}
              handleBillNoData={this.handleBillNoData.bind(this)}
              handleModalPane={this.handleModalPane.bind(this)}
              handleRecordKey={this.handleRecordKey.bind(this)}
              handleSelectChange={this.handleSelectChange.bind(this)}
              onModalClose={this.handlePpopUpPaneCancel}
              oniYear={this.handleiYear}
            />
            <Modal
              title={Object.keys(this.state.modalPanel).length > 0 ? this.state.modalPanel.title : ''}
              visible={this.state.modalVisible}
              onCancel={this.handlePpopUpPaneCancel.bind(this)}
              footer={null}
              width={1000}
              wrapClassName={styles.modal}
            >
              <PpopupPan handleGetResult={this.handleGetResult} />
            </Modal>
          </div>}
        </Spin>
      </div>
    );
  }
}

const SystemSettingComponent = Form.create({
  mapPropsToFields(props) {
    const { systemData, masterShowConfig } = props;
    const obj = commonFunc.sysPropsToFieldsChangeValue(masterShowConfig, systemData, Form);
    // console.log('object', obj);
    return obj;
  },
  onValuesChange(props, changedFields) {
    props.onChange(changedFields);
  },
})((props) => {
  const { app, form } = props;
  const {
    sActiveId,
    masterConfig,
    sId,
    formData,
    dispatch,
    handleCancel,
    handleSubmit,
    changeDataFlag,
    handleModalPane,
    handleSelectChange,
    content,
    handleAccountData,
    handleBillNoData,
    handleRecordKey,
    accountData,
    billnoData,
    oldBillNoData,
    listRecordKey,
    systemData,
    iYear,
    oniYear,
  } = props;
  /* 主表 */
  const { handleForm, onModalClose } = props;
  const onClose = onModalClose;
  const childProps = {
    app, form, sActiveId, sId, dispatch, content, masterConfig, handleModalPane, handleSelectChange, onClose,
  };
  const mainProps = {
    formData,
    componentName: 'syssystemsettings',
    ...childProps,
    changeDataFlag,
    dataName: 'systemData',
    dataType: 'Map',
    dataSet: systemData,
  };
  /* 页签 */
  const {
    tabFinancePeriod, tabReceiptsNum, tabFinanceOffer, tabSalesBuyer, tabSysParam,
  } = props;
  /* 会计期间表配置 refreshList用于弹窗数据回填后需要放行刷新动作 dataList列表数据下放 */
  const accountConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'sysaccountperiod'))[0];
  const accountProps = {
    iYear,
    formData,
    componentName: 'sysaccountperiod',
    ...childProps,
    handleRecordKey,
    handleAccountData,
    masterConfig: accountConfig !== undefined ? accountConfig : { sId: '' },
    dataExist: Object.keys(accountData).length > 0,
    dataName: 'accountData',
    dataType: 'List',
    dataList: accountData,
    refreshList: listRecordKey.accountDataKey === '',
    oniYear,
  };
  /* 单据编号表配置 refreshList用于弹窗数据回填后需要放行刷新动作 dataList列表数据下放 */
  const billnoConfig = formData.filter(item => (item.sTbName.toLowerCase() === 'sysbillnosettings'))[0];
  const billnoProps = {
    formData,
    componentName: 'sysbillnosettings',
    ...childProps,
    handleRecordKey,
    handleBillNoData,
    masterConfig: billnoConfig !== undefined ? billnoConfig : { sId: '' },
    dataExist: Object.keys(billnoData).length > 0,
    dataName: 'billnoData',
    dataType: 'List',
    dataList: billnoData,
    dataListSearch: oldBillNoData,
    refreshList: listRecordKey.billnoDataKey === '',
  };
  return (
    <Form>
      <Layout>
        <Header className={styles.header}>
          <Toolbar
            componentName="toolsystem"
            {...props}
            onBtnCancel={handleCancel}
            onSubmit={handleSubmit}
          >
            {handleForm(form)}
          </Toolbar>
        </Header>
      </Layout>
      <Layout className={styles.clayout}>
        <Content className={styles.content}>
          <div id="slaveTabs">
            <Tabs className={styles.slaveTabs}>
              <TabPane tab={tabFinancePeriod.showName} key={1}>
                <TabFinancePeriod {...accountProps} />
              </TabPane>
              <TabPane tab={tabSalesBuyer.showName} key={2} forceRender>
                <TabsSalesBuyer {...mainProps} />
              </TabPane>
              <TabPane tab={tabFinanceOffer.showName} key={3} forceRender>
                <TabFinanceOffer {...mainProps} />
              </TabPane>
              <TabPane tab={tabReceiptsNum.showName} key={4} forceRender>
                <TabReceiptsNum {...billnoProps} />
              </TabPane>
              <TabPane tab={tabSysParam.showName} key={5} forceRender>
                <TabSysParam {...mainProps} />
              </TabPane>
            </Tabs>
          </div>
        </Content>
      </Layout>
    </Form>
  );
});

export default baseHigher(SystemSetting);
